package com.dhy.payutil.alipay;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dhy.payutil.PayCallback;
import com.dhy.payutil.PayStatus;
import com.dhy.payutil.R;

/**
 * You need set alipay_partner, alipay_seller, alipay_rsa_private in string file.<p/>
 */
public class AlipayHelper {
	private final String RSA_PRIVATE;
	private final String PARTNER;
	private final String SELLER;
	protected Activity activity;

	/**
	 * You need set alipay_partner, alipay_seller, alipay_rsa_private in string file
	 */
	public AlipayHelper(Activity activity) {
		this(activity, R.string.alipay_partner, R.string.alipay_seller, R.string.alipay_rsa_private);
	}

	private AlipayHelper(Activity activity, int partner_rid, int seller_rid, int rsa_private_rid) {
		this.activity = activity;
		this.RSA_PRIVATE = activity.getString(rsa_private_rid);
		this.PARTNER = activity.getString(partner_rid);
		this.SELLER = activity.getString(seller_rid);
	}

	public void pay(String goods, String description, float money, String out_trade_no, String notify_url, PayCallback callback) {
		AlipayInfo info = new AlipayInfo();
		info.subject = goods;
		info.body = description;
		info.total_fee = String.valueOf(money);
		info.out_trade_no = out_trade_no;
		info.notify_url = notify_url;
		pay(info, callback);
	}

	public void pay(final AlipayInfo payInfo, final PayCallback callback) {
		pay(payInfo, false, callback);
	}

	public void pay(final AlipayInfo payInfo, final boolean bankCard, final PayCallback payCallback) {
		if (!validSettings(PARTNER, SELLER, RSA_PRIVATE)) return;
		final String info;
		try {
			info = payInfo.toString(PARTNER, SELLER, bankCard, RSA_PRIVATE);
		} catch (Exception e) {
			e.printStackTrace();
			if (!activity.isFinishing()) payCallback.callback(PayStatus.dataError);
			return;
		}
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				return new PayTask(activity).pay(info, false);//isShowPayLoading
			}

			@Override
			protected void onPostExecute(String result) {
				if (!activity.isFinishing()) payCallback.callback(parsePayResult(result));
			}
		}.execute();
	}

	private boolean validSettings(String... settings) {
		for (String s : settings) {
			if (s.length() < 3) {
				Toast.makeText(activity, "You need set alipay_partner, alipay_seller, alipay_rsa_private in string file. See " + getClass().getSimpleName() + "'s DOC for more detail", Toast.LENGTH_LONG).show();
				return false;
			}
		}
		return true;
	}

	private PayStatus parsePayResult(String result) {
		AlipayResult r = new AlipayResult(result);
		if (r.resultStatus != null) {
			switch (r.resultStatus) {
				case "9000":
					return PayStatus.ok;
				case "8000":
					return PayStatus.waiting;
			}
		}
		return PayStatus.failed;
	}
}
